/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.digwener.db;

/**
 *
 * @author Anton
 */
import com.digwener.entities.connectors.ConnectorType;

import java.sql.Connection;
//import sun.jdbc.odbc.ee.ConnectionHandler;

import java.sql.*;
import java.util.*;
import javax.swing.JOptionPane;

public class DBConnection {
    
    private static DBConnection instance = new DBConnection();
    
    Map<String,String> passwords = new HashMap();
    
    private ConnectorType connector;
    Connection connection = null;
    
    private String password = "";
    
    private DBConnection(){
        
    }
    
    public static DBConnection getInstance(){
        return instance;
    }
    
    public void setPassword(String password){
        
        if(connector != null){
            String instance = connector.getInstanceName();
            passwords.put(instance,password);
            this.password = password;
        }
        
    }

    public ConnectorType getConnector() {
        return connector;
    }

    public void setConnector(ConnectorType connector) {
        this.connector = connector;
    }
    
    public void connect(){
          try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);
            // Create a connection to the database
            String instanceName = connector.getInstanceName();
            String serverName = connector.getServerName();
            String portNumber = connector.getPortNumber();
            String sid = connector.getSid();
            String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
            String username = connector.getUserName();
            System.out.println("username: ["+username+"] ");
            if(passwords.containsKey(instanceName)){
                password = passwords.get(instanceName);
            } else {
                
                String a = JOptionPane.showInputDialog(null,"Password:");
                
                setPassword(a);
            }
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFound");
        } catch (SQLException e) {
            System.out.println(e.toString());
        }
    }
    
    public void disconnect(){
        
    }
    
    public Connection getSQLConnection(){
       return connection;
    }
    
    public boolean isConnected(){
        
        if(connection == null){
            return false;
        }
        try{
        return connection.isValid(0);
        } catch (SQLException e){
            return false;
        }
        
    }
    
    
}
